#include "tcpserver.h"

TcpServer::TcpServer()
{

}

TcpServer::~TcpServer()
{

}
// 关闭所有socket
void TcpServer::clearClientAll()
{
    for (QString key : socketArray.keys())
    {
        socketArray[key]->close();
    }
    socketArray.clear();
}

void TcpServer::sendMessage(QString socketId, QByteArray message)
{
    if(socketArray.contains(socketId))
    {
        socketArray[socketId]->sendMessage(message);
    }
}
// 关闭指定socket
void TcpServer::closeSocket(QString socketId)
{
    if(socketArray.contains(socketId))
    {
        socketArray[socketId]->close();
    }
}

// 重写incomingConnection，当有链接的时候，为这个socket设置标记
void TcpServer::incomingConnection(qintptr socketId)
{
   // 创建socket
   TcpSocket *pTcpSocket = new TcpSocket();
   // 设置描述符
   pTcpSocket->setSocketDescriptor(socketId);
   QString sClientInfo =  "ID:"+QString::number(socketId) + ",IP:" + pTcpSocket->peerAddress().toString() + ":"+ QString::number(pTcpSocket->peerPort());
   // 设置ID
   pTcpSocket->setSocketID(sClientInfo);
   // 将socket加入到map
   socketArray.insert(sClientInfo,pTcpSocket);
   // 绑定读信号
   connect(pTcpSocket,SIGNAL(socket_signal_readMessage(QString)),this, SLOT(server_slot_readMessage(QString)));
   // 绑定关闭信号
   connect(pTcpSocket, SIGNAL(socket_signal_disconnected(QString)), this, SLOT(server_slot_disconnected(QString)));
   // 绑定写信号
   connect(pTcpSocket, SIGNAL(socket_signal_bytesWritten(QString, qint64)), this, SLOT(server_slot_bytesWritten(QString, qint64)));
   // 发送信号，通知上层有连接
   emit server_signal_incomingConnect(sClientInfo);
}

void TcpServer::server_slot_readMessage(QString socketId)
{
    // 发送信号，通知上层有数据
    emit server_signal_readMessage(socketId);
}

void TcpServer::server_slot_bytesWritten(QString socketId, qint64 bytes)
{
    emit server_signal_bytesWritten(socketId, bytes);
}

void TcpServer::server_slot_disconnected(QString socketId)
{
   // 发送信号，通知上层连接已关闭
   emit server_signal_disconnected(socketId);
}
